<?php
class db_users
{
	function __construct()
	{
		Global $lib, $mySql, $auth;
		$this->lib = $lib;
		$this->auth = $auth;
		$this->mySql = $mySql;
	}
	
	/*
	*	Creates a user 
	*	Required Fields : Username, Password, Email Address
	*/
	public function addUser($data)
	{
		// Create a User
		db_users::changeUser("create",$data);
		
		// Return if the request failed
		return $this->mySql->listErrors();
		
	}
	
	/*
	*	Modifies a User
	*	Required Fields : Field Name, Value, and User ID
	*/
	public function modifyUser($data)
	{
		// Create a User
		db_users::changeUser("modify",$data);
		
		// Return if the request failed
		return $this->mySql->listErrors();
		
	}
	
	/*
	*	Deletes a User
	*	Required Fields : User ID
	*/
	public function deleteUser($id)
	{
	
		// Delete User
		db_users::changeUser("delete", $id);
		
		// Return if the request failed
		return $this->mySql->listErrors();
		
	}
	
	
	
	// Account Creation
	private function createTempUser($username)
	{
		$sql = "INSERT INTO users (Username, Password, Email_Addr, Type, Time_TS) VALUES ('%s', 'NA', 'NA', 'temp', '".time()."')";
		$query = sprintf($sql,
            mysql_real_escape_string($username));
		$this->mySql->makeQuery($query);
	}
	private function changeUser($action, $data)
	{
		if("create" == $action)
		{
			$sql = "INSERT INTO users (Username, Password, Email_Addr, Type, Time_TS) VALUES ('%s', '%s', '%s', 'full', '".time()."')";
			$query = sprintf($sql,
	            mysql_real_escape_string($data[username]),
	            mysql_real_escape_string($data[password]),
				mysql_real_escape_string($data[email]));
			$this->mySql->makeQuery($query);
			$sql = "INSERT INTO prefrences (User_ID) VALUES (%d)";
			$query = sprintf($sql,
	            mysql_real_escape_string($this->mySql->insertID()));
			$this->mySql->makeQuery($query);
		}
		elseif("modify" == $action)
		{
			$sql = "UPDATE users SET %s='%s WHERE Tbl_ID=%d";
			$query = sprintf($sql,
	            mysql_real_escape_string($data[field]),
	            mysql_real_escape_string($data[value]),
				mysql_real_escape_string($data[id]));
			$this->mySql->makeQuery($query);
		}
		elseif("delete" == $action)
		{
			$sql = "UPDATE users SET Type='inactive' WHERE Tbl_ID='%s'";
			$query = sprintf($sql,
	            mysql_real_escape_string($data));
			$this->mySql->makeQuery($query);
		}
	}
	public function chkUsernameExists($username)
	{
		$sql = "SELECT * FROM users WHERE username='%s'";
		$query = sprintf($sql,
            mysql_real_escape_string($username));
		$result = $this->mySql->makeQuery($query);	
		if(0 == mysqli_num_rows($result))
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
}